package com.hd.trans.share;

import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.hd.trans.R;
import com.hd.trans.utils.DeviceUtil;

import org.jetbrains.annotations.NotNull;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableSource;
import io.reactivex.rxjava3.functions.Function;
import io.reactivex.rxjava3.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.http.Body;
import retrofit2.http.POST;

/**
 * 文件转pdf请求
 */
public class TextToPdfRequest extends BaseRetrofitRequest {
    private final String tag = "TextToPdfRequest";

    public TextToPdfRequest() {
    }

    /**
     * 参数配置
     */
    private RequestBody obtainBean(@NotNull TextToPdfParam params) {
        long serviceTime = PublicBeanManager.getInstance().getServiceTime();
        final Map<String, Object> arguments = new HashMap<>();
        arguments.put("deviceid", DeviceUtil.getDeviceId());
        arguments.put("timestamp", serviceTime);
        arguments.put("productinfo", PublicBeanManager.mProductInfo);

        arguments.put("filetype", params.getFileType());
        arguments.put("txtcontent", params.getTxtContent());
        arguments.put("width", params.getWidth());
        arguments.put("height", params.getHeight());
        arguments.put("filename", params.getFileName());
        String language = params.getTxtlanguage();
        if (!TextUtils.isEmpty(language)) {
            arguments.put("txtlanguage", language);
        }

        String md5Json = ReqUtil.appendArgumentMapToMd5String(arguments);
        arguments.put("datasign", Md5Util.getMD5(md5Json));

        //AIGC信息，不参与签名
        AIGCInfo aigcInfo = new AIGCInfo(1, "2", "xunjiepdfwebui", "翻译SDK");
        arguments.put("aigcinfo", aigcInfo);

        final String json = new Gson().toJson(arguments);
        Log.w(tag, "" + json + " md5Json：" + md5Json);
        return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
    }

    /***
     * 请求txt转doc
     */
    public Observable<TextToPdfBean> postRequest(@NotNull TextToPdfParam params) {
        RequestBody requestBody = obtainBean(params);
        return SingleRetrofitProvider.getInstance().getBaseUrlRetrofit()
                .create(MyService.class)
                .postRequest(requestBody)
                // 解析结果
                .flatMap((Function<String, ObservableSource<TextToPdfBean>>) this::parseResult)
                .doOnError(throwable -> Log.d(tag, "" + throwable.getMessage()))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }


    /**
     * 解析 [json] 数据并转为  TextToPdfBean
     *
     * @param json
     * @return
     */
    private Observable<TextToPdfBean> parseResult(String json) throws Exception {
        Log.d(tag, "parseResult " + json);
        if (TextUtils.isEmpty(json)) {
            return Observable.error(new HuDunThrowable(mAppContext.getString(R.string.toast_please_use_in_net)));
        }
        TextToPdfBean bean = new Gson().fromJson(json, TextToPdfBean.class);
        if (bean.getCode() == NetCode.RESULT_SUCCESS) {
            return Observable.just(bean);
        } else {
            return Observable.error(new HuDunThrowable(mAppContext.getString(R.string.request_fail) + bean.getCode()));
        }
    }


    private interface MyService {
        /**
         * OCR转文件
         */
        @POST("api/v4/ocrtofile")
        Observable<String> postRequest(@Body RequestBody requestBody);
    }
}
